// pages/channel/index/index.js
// 引入 QCloud 小程序增强 SDK
Date.prototype.format = function(format){ 
	var o = { 
	"M+" : this.getMonth()+1, //month 
	"d+" : this.getDate(), //day 
	"h+" : this.getHours(), //hour 
	"m+" : this.getMinutes(), //minute 
	"s+" : this.getSeconds(), //second 
	"q+" : Math.floor((this.getMonth()+3)/3), //quarter 
	"S" : this.getMilliseconds() //millisecond 
	} 

	if(/(y+)/.test(format)) { 
	format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
	} 

	for(var k in o) { 
	if(new RegExp("("+ k +")").test(format)) { 
	format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); 
	} 
	} 
	return format; 
}

var qcloud = require('../../../vendor/qcloud-weapp-client-sdk/index');

// 引入配置
var config = require('../../../config');

// 显示繁忙提示
var showBusy = text => wx.showToast({
    title: text,
    icon: 'loading',
    duration: 10000
});

// 显示成功提示
var showSuccess = text => {
    wx.hideToast();
    wx.showToast({
        title: text,
        icon: 'success'
    });
};

// 显示失败提示
var showModel = (title, content) => {
    wx.hideToast();

    wx.showModal({
        title,
        content: JSON.stringify(content),
        showCancel: false
    });
};

var showMsg = (title, content) => {
    wx.hideToast();

    wx.showModal({
        title,
        content: content,
        showCancel: false
    });
};


var busy=false;
//获取应用实例
var app = getApp()
Page({
  data:{
    userInfo: {},
    loading:false,
    loading_more:false,
    loading_show:false,
    users_count:0,
    next_data:true,
    busy:false,
    posts:[]
  },
  post_list:function(){
    var self = this;
    if(self.data.busy){
      return;
    }
    self.setData({
        loading:true,
        posts:[],
        busy:true
    });
    var url=config.service.apiUrl+'timeline';
    qcloud.request({
        // 要请求的地址
        url: url,
        success(result) {
            if(result.data.success==true){
                for (var i=0;i<result.data.posts.data.length;i++){
                  var datestr=Date.parse((result.data.posts.data[i]['created_at']).toString().replace(/-/g,   "/"));
                  if(datestr){
                    result.data.posts.data[i]['created_at']=new Date(datestr).format("hh:mm");
                  }else{
                    result.data.posts.data[i]['created_at']= '--:--'
                  }
                }
                self.setData({
                    posts:result.data.posts.data
                })
            }
            if(result.data.posts.next_page_url!==null){
                self.setData({
                    next_data:true,
                    next_page_url:result.data.posts.next_page_url
                })
            }else{
                self.setData({
                    next_data:false,
                    next_page_url:null
                })
            }
            console.log('request success', result);
        },

        fail(error) {
            console.log('request fail', error);
        },

        complete() {
           busy=false;
            self.setData({
                loading:false,
                busy:false
            })
            console.log('request complete');
        }
    });
  },
  user_list(){
    var self=this;
    var url=config.service.apiUrl+'followers';
    qcloud.request({
        // 要请求的地址
        url: url,
        success(result) {
            if(result.data.success==true){
                self.setData({
                    users_count:result.data.followers.total
                })
            }
            console.log('request success', result);
        },

        fail(error) {
            console.log('request fail', error);
        },

        complete() {
            console.log('request complete');
        }
    });
  },
  refresh(){
      var self = this;
    if(self.data.busy){
      return;
    }
    self.setData({
        loading:true,
        posts:[],
        busy:true
    });
    // wx.showNavigationBarLoading();
    var url=config.service.apiUrl+'timeline';
    qcloud.request({
        // 要请求的地址
        url: url,
        success(result) {
            if(result.data.success==true){
                for (var i=0;i<result.data.posts.data.length;i++){
                  var datestr=Date.parse((result.data.posts.data[i]['created_at']).toString().replace(/-/g,   "/"));
                  if(datestr){
                    result.data.posts.data[i]['created_at']=new Date(datestr).format("hh:mm");
                  }else{
                    result.data.posts.data[i]['created_at']= '--:--'
                  }
                }
                self.setData({
                    posts:result.data.posts.data
                })
            }
            if(result.data.posts.next_page_url!==null){
                self.setData({
                    next_data:true,
                    next_page_url:result.data.posts.next_page_url
                })
            }else{
                self.setData({
                    next_data:false,
                    next_page_url:null
                })
            }
            console.log('request success', result);
        },

        fail(error) {
            console.log('request fail', error);
        },

        complete() {
            self.setData({
                loading:false,
                busy:false
            });
            // wx.hideNavigationBarLoading();
            wx.stopPullDownRefresh();
            console.log('request complete');
        }
    });
  },
  load_more(){
      var self = this;
      var request_url=self.data.next_page_url;
      if(!request_url){
          return;
      }
      if(self.data.busy){
        return;
      }
      self.setData({
        loading:true,
        busy:true
      });
      qcloud.request({
          // 要请求的地址
          url: request_url,
          success(result) {
              if(result.data.success==true){
                  var item=self.data.posts;
                  var obj=result.data.posts.data;
                  for (var i=0;i<obj.length;i++){
                    var datestr=Date.parse((obj[i]['created_at']).toString().replace(/-/g,   "/"));
                    if(datestr){
                      obj[i]['created_at']=new Date(datestr).format("hh:mm");
                    }else{
                      obj[i]['created_at']= '--:--'
                    }
                    item.push(obj[i]);
                  }
                  self.setData({
                      posts:item
                  });
                  if(result.data.posts.next_page_url!==null){
                      self.setData({
                          next_data:true,
                          next_page_url:result.data.posts.next_page_url
                      })
                  }else{
                      self.setData({
                          next_data:false,
                          next_page_url:null
                      })
                  }
              }
              console.log('request success', result);
          },

          fail(error) {
              console.log('request fail', error);
          },

          complete() {
              self.setData({
                  loading:false,
                  busy:false
              })
              console.log('request complete');
          }
    });
  },
  formSubmit:function(e){
    var self = this;
    if(self.data.busy1){
      return;
    }
    var data={};
    data.image_url="http://upload-1251348966.image.myqcloud.com/upload/2017-04-21/b1ba2fd7b035f7db742bf76e2af7be96.png?imageMogr2/auto-orient/strip/thumbnail/1000x1000/quality/80/format/jpg";
    if(e.detail.formId!='the formId is a mock one'){
      data.form_id=e.detail.formId;
    }
    data.can_read_times=-1
    data.type==1
    data.expire_in=-1;
    self.setData({
        'busy1':true
    })
    qcloud.request({
            // 要请求的地址
            url: config.service.messageAddUrl,
            method:"POST",
            data: data,
            success(result) {
              console.log(result);
              if(result.data.success==true){
                wx.navigateTo({
                    url: '/pages/channel/invitation/invitation?hash_key='+result.data.id
                 })
              }else{
                showMsg("提示信息","新建邀请失败，"+result.data.message);
              }
            },

            fail(error) {
                console.log('request fail', error);
                showMsg("提示信息","新建邀请失败");
            },

            complete() {
                self.setData({
                      'busy1':false
                  })
                console.log('request complete');
            }
      });
  },
  onReachBottom: function() {
    var self = this;
    self.load_more();
  },
  onPullDownRefresh: function() {
    var self = this;
    self.refresh();
  },
  onLoad:function(e){
      console.log(e);
      if(e.hash_key){
        this.setData({
            hash_key:e.hash_key
        })
        var self=this;
      }else{
          console.log('123')
      }
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady:function(){
    // 页面渲染完成
  },
  onShow:function(){
    // 页面显示
    var self=this;
    if(busy){
      return;
    }
    self.setData({
        posts:[],
        loading:true,
        busy:false
    });
    busy=true;
    var self=this;
    app.getUserInfo(function(userInfo){
      self.setData({
          userInfo:userInfo
      });
      self.post_list();
      self.user_list();
      if(self.data.hash_key==undefined||!self.data.hash_key){
          return false;
      }
      qcloud.request({
            // 要请求的地址
            url: config.service.apiUrl+'messages/'+self.data.hash_key,
            success(result) {
              console.log(result);
              if(result.data.success==true){
                  if(result.data.is_mine==false){
                      var ncikname=result.data.message_data.user.nickname;
                      showMsg("提示信息","您成功关注了"+ncikname+'的密频');
                  }
              }
                  
            },

            fail(error) {
                console.log('request fail', error);
            },

            complete() {
                console.log('request complete');
            }
      });
    });
  },
  formSubmit1: function(e) {
      var self=this;
      var url=e.detail.target.dataset.url;
      var data={};
      if(e.detail.formId!='the formId is a mock one'){
        data.form_id=e.detail.formId;
      }else{
          wx.navigateTo({
                url: url
           });
           return;
      }
      data.openid=self.data.userInfo.openId;
      qcloud.request({
        // 要请求的地址
        url: config.service.apiUrl+'form_ids',
        method:"POST",
        data: data,
        success(result) {
            console.log(result);
            
        },
        fail(error) {
            console.log('request fail', error);
        },
        complete() {
            wx.navigateTo({
                url: url
            })
        }
      });
  },
  onHide:function(){
    // 页面隐藏
  },
  onUnload:function(){
    // 页面关闭
  }
})